<template>
  <div>
    {{ name }}
    <br />
    {{ age }}
    <br />
    <button @click="changeName">changeName</button>
    <button @click="changeAge">changeAge</button>
  </div>
</template>

<script>
import { ref, watchEffect } from 'vue'
export default {
  setup() {
    const name = ref('code')
    const age = ref(18)

    const changeName = () => {
      name.value = 'fly'
    }
    const changeAge = () => {
      age.value += 1
    }
    // 侦听数据、定义之后先执行一次，当数据发生改变的时候继续侦听
    // stop返回值 可以设置设置的临界点之后，停止侦听
    const stop = watchEffect((onInvalidate) => {
      const timer = setTimeout(() => {
        console.log('订阅')
      }, 1000)

      onInvalidate(() => {
        console.log('取消订阅')
        clearTimeout(timer)
      })
      console.log(name.value)
      console.log(age.value)
      if (age.value === 26) stop()
    })

    return {
      name,
      age,
      changeName,
      changeAge,
    }
  },
}
</script>

<style
  lang="scss"
  scoped
></style>
